<?php

namespace service\express\DataSources;

use service\express\DataSourceAbstract;

class City100Default extends DataSourceAbstract
{
    protected $request_uri = 'http://58.83.226.244/Express_NET_BJFX/UI/Track/TrackPOD_Comm100.aspx';

    /**
     * getData
     *
     * @param string $express_no
     * @param null $brand
     * @return mixed
     */
    public function getData($express_no, $brand = null)
    {
        $post_data = [
            'txtJobNoList' => $express_no,
            'btnQuery' => '确认查询',
            'RdList' => 0,
        ];
        if ($tokens = $this->getToken()) {
            if (is_array($tokens)) {
                $post_data = array_merge($post_data, $tokens);
            }
            $this->request_params = $post_data;
            if ($this->origin_return = static::$requester->post($this->request_uri, $post_data)) {
                return $this->parseResponse($this->origin_return);
            }
            $this->setError(static::$requester->getError(), 'get_result_curl_errr');
            return false;
        }
        $this->setError('failed to get session token');
        return false;
    }

    /**
     * parseResponse from data source
     *
     * @param null|string $data
     * @return mixed
     */
    protected function parseResponse($data = null)
    {
        if (is_string($data)) {
            $result = array();
            $pattern = "/<td\s+bgColor='#eff5fb'>点货资料<\/td><\/tr>\s*<tr\s+align=middle>\s*(.*)<\/tr>\s*<\/table><BR>/isU";
            $is_matched = preg_match_all($pattern, $data, $matches);
            if ($is_matched) {
                $pattern = "/<td\s+align=center\s+bgColor='#FFFFFF'>(.*)<\/td>\s*<td\s+bgColor='#FFFFFF'\s+align=left>(.*)<\/td>/isU";
                $is_matched = preg_match_all($pattern, $matches[1][0], $matches2);
                if ($is_matched) {
                    foreach ($matches2[1] as $k => $v) {
                        $result[] = $v . ' ' . $matches2[2][$k];
                    }
                }
            }
            return $result;
        }
    }

    /**
     * getToken
     *
     * @todo store session in memory
     * @return string|boolean
     */
    private function getToken()
    {
        if ($return = static::$requester->get($this->request_uri)) {
            $tokens = [
                '__VIEWSTATE' => '',
                '__VIEWSTATEGENERATOR' => '',
            ];
            $pattern_tpl = "#%s[\"\'][^>]+value=[\"\'](.*)[\"\']#i";
            foreach ($tokens as $key => $val) {
                if (preg_match(sprintf($pattern_tpl, $key), $return, $match)) {
                    $tokens[$key] = $match[1];
                } else {
                    $this->setError('fail to get token:' . $key, 'get_token');
                    return false;
                }
            }
            return $tokens;
        }
        $this->setError(static::$requester->getError(), 'get_token_curl_error');
        return false;
    }
}
